package com.xr.framework.miniprogram.service;

import com.xr.common.constant.CacheConstants;
import com.xr.common.constant.Constants;
import com.xr.common.core.redis.RedisCache;
import com.xr.common.utils.StringUtils;
import com.xr.common.utils.uuid.IdUtils;
import com.xr.miniprogram.domain.vo.MiniProgramUserVO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class UserTokenService {
    @Autowired
    private RedisCache redisCache;
    protected static final long MILLIS_SECOND = 1000;
    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;
    @Value("${wxlogin.secret}")
    public String secret;
    // 令牌自定义标识
    @Value("${token.header}")
    private String header;
    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
    private static final Long MILLIS_MINUTE_TEN = 20 * 60  * 1000L;
    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public MiniProgramUserVO getLoginUser(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            try
            {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                String userKey = getTokenKey(uuid);
                MiniProgramUserVO user = redisCache.getCacheObject(userKey);
                return user;
            }
            catch (Exception e)
            {
            }
        }
        return null;
    }
    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }
    private String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    public String createToken(MiniProgramUserVO miniProgramUserVO)
    {
        String token = IdUtils.fastUUID();
        miniProgramUserVO.setToken(token);
        setUserAgent(miniProgramUserVO);
        refreshToken(miniProgramUserVO);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        return createToken(claims);
    }
    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param
     * @return 令牌
     */
    public void verifyToken(MiniProgramUserVO miniProgramUserVO)
    {
        long expireTime = miniProgramUserVO.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(miniProgramUserVO);
        }
    }
    public void refreshToken(MiniProgramUserVO miniProgramUserVO)
    {
        miniProgramUserVO.setLoginTime(System.currentTimeMillis());
        miniProgramUserVO.setExpireTime(miniProgramUserVO.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(miniProgramUserVO.getToken());
        redisCache.setCacheObject(userKey, miniProgramUserVO,expireTime, TimeUnit.MINUTES);
    }

    private String getTokenKey(String uuid)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }
    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims)
    {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }
    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    public void setUserAgent(MiniProgramUserVO loginUser)
    {
        loginUser.setCode(loginUser.getCode());
        loginUser.setLoginTime(loginUser.getLoginTime());
        loginUser.setExpireTime(loginUser.getExpireTime());
    }
}
